package com.design3.graduatethesissys.mapper;

import com.design3.graduatethesissys.domain.Message;
import com.design3.graduatethesissys.domain.SysUser;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@Mapper
public interface MessageMapper {
    @Select("SELECT * FROM sys_user WHERE username=#{username};")
    SysUser findByUserName(String userName);
    @Insert("insert into message(mes_id,from_id,from_name,to_id,to_name,content,date,mes_status) " +
            "values (#{mes_id},#{from_id},#{from_name},#{to_id},#{to_name},#{content},#{date},#{mes_status})")
    void insertMessage(Message message);
    @Select("SELECT * FROM message WHERE to_id=#{myId} and mes_status='zt01';")
    List<Message> getMyNewMessage(String myId);
    
    @Select("SELECT * FROM message WHERE (to_id=#{myId} and from_id=#{yourId}) or (from_id=#{myId} and to_id=#{yourId}) order by date desc limit 10;")
    List<Message> getMessageByFromId(String myId,String yourId);
    
    @Select("SELECT * FROM message WHERE (to_id=#{myId} and from_id=#{yourId}) and mes_status='zt01' order by date desc limit 10;")
    List<Message> getNewMessageById(String myId, String yourId);
    
    @Select("SELECT * FROM message WHERE (to_id=#{myId} and from_id=#{yourId}) and mes_status='zt01' order by date desc;")
    List<Message> getAllNewMessageById(String myId, String yourId);
    
    @Update({
            "<script>"
                    + "UPDATE message SET mes_status = 'zt02' WHERE mes_id in "
                    + "<foreach item='item' index='index' collection='collections' open='(' separator=',' close=')'>"
                    +       "#{item.mes_id}"
                    + "</foreach>"
                    +"</script>"
    })
    void updateStatus(@Param("collections") List<Message> messages);
    @Update({
            "<script>"
                    + "UPDATE message SET mes_status = 'zt02' WHERE to_id='myId' and mes_id in "
                    + "<foreach item='item' index='index' collection='collections' open='(' separator=',' close=')'>"
                    +       "#{item.mes_id}"
                    + "</foreach>"
                    +"</script>"
    })
    void updateMyMessages(@Param("collections") List<Message> messages,@Param("myId") String myId);
    
    @Select("SELECT\r\n" + 
    		"	count(*) \r\n" + 
    		"FROM\r\n" + 
    		"	message \r\n" + 
    		"WHERE\r\n" + 
    		"	from_id = #{from_id} \r\n" + 
    		"	AND to_id = #{id} \r\n" + 
    		"	AND mes_status = \"zt01\"")
	Map<String, Object> getCountMessage(String id, String from_id);
}
